package com.android.lovely.ui.fragment.role

import android.os.Bundle
import android.view.View
import androidx.activity.addCallback
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.viewbinding.ViewBinding
import com.android.lovely.R
import com.android.lovely.databinding.FragmentCreateRoleOneBinding
import com.android.lovely.framework.BaseFragment
import com.android.lovely.room.role.CreateRole
import com.android.lovely.ui.dialog.showLovelyDialog
import com.android.lovely.ui.viewmodel.CreateRoleViewModel
import com.kotlin.extensions.appContext
import com.kotlin.extensions.context.ContextExt.windowWidth
import com.kotlin.extensions.dimen.Dimension.dp
import com.kotlin.extensions.dimen.Dimension.dpF
import com.kotlin.extensions.keyboard.hideKeyboard
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 *
 * @author why
 * @date 2025/4/6 21:20
 */
val bottomHeight = ((appContext.windowWidth - 30.dpF) / (354 / 55f)).toInt() + 30.dp

abstract class CreateRoleBaseFragment<VB : ViewBinding> : BaseFragment<VB>()  {
    val viewModel by activityViewModels<CreateRoleViewModel>()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (viewModel.isEdit) {
            requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) {
                if (hasEdit() && !viewModel.isQuick) {
                    requireActivity().hideKeyboard()
                    requireActivity().showLovelyDialog {
                        setDialogTitle(getString(R.string.discard_change))
                        setPositiveButton(getString(R.string.sure)) {
                            activity?.finish()
                        }
                    }
                    return@addCallback
                }
                activity?.finish()
            }
        }
        viewModel.createRole?.let { update(it) }

        lifecycleScope.launch {
            viewModel.createRoleFlow.collectLatest {
                update(it)
            }
        }
    }
    abstract fun save()
    abstract fun hasEdit(): Boolean
    abstract fun onKeyBoardChange(progress: Int)

    abstract fun update(it: CreateRole)
}